/**
 * [1 Timothy 3:16-17 ESV]
 * All Scripture is breathed out by God and profitable
 * for teaching, for reproof, for correction, and for training in righteousness,
 * that the man of God may be complete, equipped for every good work.
 *
 * BibleReader is an simple application for you to study God's Word.
 * The main user of this application maybe the pastor who's main language
 * is Chinese Simplified.
 *
 * You can use it totally free, and if you want to get source code of
 * this application, please email me at dweng123@gmail to get the source
 * code.
 *
 */
#include <QMouseEvent>
#include <QMenu>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include "bibleverse.h"
#include "biblesearchresultwidget.h"
#include "biblesearchwidget.h"

BibleSearchResultWidget::BibleSearchResultWidget(BibleReaderCore *brc, QWidget *parent) :
    QTreeWidget(parent)
{
    brCore = brc;

    queryResults.clear();
}

void BibleSearchResultWidget::addResult(int key, QList<BibleVerse> result)
{
    if (!queryResults.contains(key)) {
        queryResults.insert(key, result);
    }
}

void BibleSearchResultWidget::removeResult(int key)
{
    if (queryResults.contains(key)) {
        queryResults.remove(key);
    }
}

bool BibleSearchResultWidget::copyCurVerseHeaderLong()
{
    QClipboard *cb = QApplication::clipboard();
    QTreeWidgetItem *current = currentItem();
    if (current->parent()) {
        BibleVerse verse = brCore->getVerse(
                    current->data(2, Qt::DisplayRole).toString(),
                    current->data(3, Qt::DisplayRole).toInt(),
                    current->data(4, Qt::DisplayRole).toInt(),
                    current->data(5, Qt::DisplayRole).toInt());
        cb->setText(verse.longHeader(), QClipboard::Clipboard);
    }
    return true;
}

bool BibleSearchResultWidget::copyCurVerseHeaderShort()
{
    QClipboard *cb = QApplication::clipboard();
    QTreeWidgetItem *current = currentItem();
    if (current->parent()) {
        BibleVerse verse = brCore->getVerse(
                    current->data(2, Qt::DisplayRole).toString(),
                    current->data(3, Qt::DisplayRole).toInt(),
                    current->data(4, Qt::DisplayRole).toInt(),
                    current->data(5, Qt::DisplayRole).toInt());
        cb->setText(verse.header(), QClipboard::Clipboard);
    }
    return true;
}

/*
void BibleSearchResultWidget::mousePressEvent(QMouseEvent *event)
{
    QModelIndex current = currentIndex();
    if (event->button() == Qt::RightButton) {
        emit clicked(current);
    } else {
        QTreeWidget::mousePressEvent(event);
    }
}
*/

void BibleSearchResultWidget::contextMenuEvent(QContextMenuEvent *event)
{
    QTreeWidgetItem *current = currentItem();
    if (current == nullptr) {
        QTreeWidget::contextMenuEvent(event);
        return;
    }

    QMenu *menu = nullptr;
    if (current->childCount() == 0) {
        menu = new QMenu(this);
        QAction *copyVerseHeaderLong = menu->addAction(tr("Copy this verse header(long book name)"));
        connect(copyVerseHeaderLong, &QAction::triggered, this, &BibleSearchResultWidget::copyCurVerseHeaderLong);

        QAction *copyVerseHeaderShort = menu->addAction(tr("Copy this verse header(short book name)"));
        connect(copyVerseHeaderShort, &QAction::triggered, this, &BibleSearchResultWidget::copyCurVerseHeaderShort);

        QAction *copyVerse = menu->addAction(tr("Copy this verse"));
        connect(copyVerse, &QAction::triggered, this, &BibleSearchResultWidget::copyCurVerse);

        QAction *cmpVerse = menu->addAction(tr("Compare this verse"));
        connect(cmpVerse, &QAction::triggered, this, &BibleSearchResultWidget::cmpVerse);

        //setCurrentVerse();
        menu->exec(event->globalPos());
        delete menu;
    } else if (current->parent() == nullptr){
        menu = new QMenu(this);

        QAction *removeCurResultAct = menu->addAction(tr("Remove current result"));
        connect(removeCurResultAct, SIGNAL(triggered(bool)), this, SLOT(removeCurResult()));
        QAction *removeAllResultsAct = menu->addAction(tr("Remove all results"));
        connect(removeAllResultsAct, SIGNAL(triggered(bool)), this, SLOT(removeAllResults()));
        QAction *exportResults = menu->addAction(tr("Export search results"));
        connect(exportResults, &QAction::triggered, this, &BibleSearchResultWidget::exportResults);
        menu->exec(event->globalPos());
        delete menu;

    }
    QTreeWidget::contextMenuEvent(event);
}

void BibleSearchResultWidget::setCurrentVerse()
{
    QTreeWidgetItem *current = currentItem();
    if (current->parent()) {

        QString version = current->data(2, Qt::DisplayRole).toString();
        int book = current->data(3, Qt::DisplayRole).toInt();
        int chapter = current->data(4, Qt::DisplayRole).toInt();
        int verse = current->data(5, Qt::DisplayRole).toInt();

        brCore->setCurrentVersion(version);
        brCore->setCurrentBCV(book, chapter, verse);
    }
}

bool BibleSearchResultWidget::copyCurVerse()
{
    QClipboard *cb = QApplication::clipboard();
    QTreeWidgetItem *current = currentItem();
    if (current->parent()) {
        BibleVerse verse = brCore->getVerse(
                    current->data(2, Qt::DisplayRole).toString(),
                    current->data(3, Qt::DisplayRole).toInt(),
                    current->data(4, Qt::DisplayRole).toInt(),
                    current->data(5, Qt::DisplayRole).toInt());
        cb->setText(verse.text(brCore->getConfigurator()->getVerseCopyTitleStyle()), QClipboard::Clipboard);
    }
    return true;
}

void BibleSearchResultWidget::cmpVerse()
{
    QTreeWidgetItem *current = currentItem();
    int b, c, v;
    if (current->parent()) {
        b = current->data(3, Qt::DisplayRole).toInt();
        c = current->data(4, Qt::DisplayRole).toInt();
        v = current->data(5, Qt::DisplayRole).toInt();
        brCore->setCurrentBCV(b, c, v);
        emit fireCmpVerse();
    }
}

void BibleSearchResultWidget::exportResults()
{
    QTreeWidgetItem *current = currentItem();
    if (current->parent() == nullptr) {
        int key = current->data(1, Qt::UserRole).toInt();

        QList<BibleVerse> result = queryResults.value(key);

        QString exportHtml = "";

        for (int i = 0; i < result.size(); i++) {
            exportHtml.append(result[i].textLongHeader(1)).append("\n");
        }

        QString path = QFileDialog::getSaveFileName(this, tr("Save search result"), ".", tr("Word Files(*.doc *.docx)"));
        if(path.length() == 0) {
            return;
        } else {
            QFile f(path);
            if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
                f.write(exportHtml.toUtf8());
                f.close();
            }
        }
    }
}

void BibleSearchResultWidget::removeCurResult()
{
    QModelIndex current = currentIndex();
    if (current.parent() == QModelIndex()) {
        takeTopLevelItem(current.row());
    }

}

void BibleSearchResultWidget::removeAllResults()
{
    clear();
}
